package com.github.defense.plugin.gray.manager;


import com.github.defense.plugin.gray.enums.GrayType;
import com.github.defense.plugin.gray.interceptor.GrayInterceptor;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Author: lettger
 * @Date: 2021/6/7 2:58 下午
 */
@Slf4j
public class DefaultGrayManager implements GrayManager {

    private Map<GrayType, List<GrayInterceptor>> map = Maps.newHashMap();
    private List<GrayInterceptor> list = Lists.newArrayList();

    @Override
    public List<GrayInterceptor> getGrayInterceptor(GrayType grayType) {
        List<GrayInterceptor> grayInterceptors = map.get(grayType);
        if (CollectionUtils.isEmpty(grayInterceptors)) {
            return list;
        }
        return grayInterceptors;
    }

    @Override
    public void setGrayInterceptors(Collection<GrayInterceptor> grayInterceptors) {
        if (!CollectionUtils.isEmpty(grayInterceptors)) {
            for (GrayInterceptor interceptor : grayInterceptors) {
                List<GrayInterceptor> interceptors = map.get(interceptor.getGrayType());
                if (CollectionUtils.isEmpty(interceptors)) {
                    interceptors = Lists.newArrayList();
                }
                interceptors.add(interceptor);
                map.put(interceptor.getGrayType(),interceptors);
            }
        }
    }
}
